//
//  MNDTransferingDetailViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/17.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDTransferingDetailViewController.h"
#import "MNDTransferDetailModel.h"
#import "MNDTransferSuccessRecordModel.h"
#import "MNDTransferSuccessCell.h"
#import "MNDInvestmentDetailHeaderView.h"
#import "MNDTransferHeaderView.h"
#import "MNDTransferFootView.h"
#import "MNDLoginUserModel.h"
#import "MNDWebViewController.h"

@interface MNDTransferingDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *transferDetailTableView;
@property (weak, nonatomic) IBOutlet UIView *noneDataView;

//转让收入
@property (weak, nonatomic) IBOutlet UILabel *incomeLabel;
//转让本金
@property (weak, nonatomic) IBOutlet UILabel *principalLabel;
//应计利息
@property (weak, nonatomic) IBOutlet UILabel *accruedInterestLabel;
//转让费用
@property (weak, nonatomic) IBOutlet UILabel *servefeeLabel;
//已转本金
@property (weak, nonatomic) IBOutlet UILabel *principaledLabel;
//标题
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
//剩余可转让本金
@property (weak, nonatomic) IBOutlet UILabel *sureTransferPrincipalLabel;
//转让折扣
@property (weak, nonatomic) IBOutlet UILabel *discountAprLabel;
//剩余期限
@property (weak, nonatomic) IBOutlet UILabel *creditorDeadlineLabel;
//转让日期
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
//年化利率
@property (weak, nonatomic) IBOutlet UILabel *yearAprLabel;

/* 债权转让模型 */
@property (strong, nonatomic) MNDTransferDetailModel *transferDetailModel;
/* 债权转让成功模型 */
@property (strong, nonatomic) NSMutableArray<MNDInvestmentSectionModel*> *tranferSuccessRecordModelArray;
@property (weak, nonatomic) IBOutlet UIImageView *statusImgView;
@end

@implementation MNDTransferingDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view layoutIfNeeded];
    [self.view setNeedsLayout];
    if ([self.transferStatus isEqualToString:@"0"]) {
        [self initialBarbuttonItems];
    }
    
    [self setupUI];
    [self loadData];
}

- (NSMutableArray<MNDInvestmentSectionModel *> *)tranferSuccessRecordModelArray {
    if (!_tranferSuccessRecordModelArray) {
        _tranferSuccessRecordModelArray = [NSMutableArray array];
    }
    
    return _tranferSuccessRecordModelArray;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"撤销转让"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(cancelTransferAction:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

#pragma mark -加载数据
- (void)loadData {
    __weak typeof(self) weakSelf = self;
    
    //转让中数据获取
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"creditor_id":self.creditorId}];
    [APIManager sendRequestWithPath:API_TENDER_TRANSFER_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakSelf.transferDetailModel = [MNDTransferDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configContents];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configContents {
    self.incomeLabel.text = self.transferDetailModel.creditor.income;
    self.principalLabel.text = self.transferDetailModel.creditor.principal;
    self.accruedInterestLabel.text = self.transferDetailModel.creditor.accrued_interest;
    self.servefeeLabel.text = self.transferDetailModel.creditor.servefee;
    self.principaledLabel.text = self.transferDetailModel.creditor.principaled;
    self.discountAprLabel.text = [NSString stringWithFormat:@"%@%%",self.transferDetailModel.creditor.discount_apr];
    self.sureTransferPrincipalLabel.text = self.transferDetailModel.creditor.sure_transfer_principal;
    self.creditorDeadlineLabel.text = self.transferDetailModel.creditor.creditor_deadline;
    self.dateLabel.text = self.transferDetailModel.creditor.date;
    
    self.titleLabel.text = self.transferDetailModel.detial_title;
    self.yearAprLabel.text = [NSString stringWithFormat:@"%@%%", self.transferDetailModel.borrow_year_apr];
    
    if(self.transferDetailModel.transfer.count > 0) {
        self.noneDataView.hidden = YES;
    }else {
        self.noneDataView.hidden = NO;
    }
    
    if (self.transferDetailModel.transfer.count > 0) {
        for (NSInteger i = 0; i < self.transferDetailModel.transfer.count; i++) {
         
            MNDTransferSuccessRecordModel *recordModel = self.transferDetailModel.transfer[i];

            MNDInvestmentSectionModel *sectionModel = [MNDInvestmentSectionModel new];
            sectionModel.transferSuccessModel = recordModel;
            if (i == 0) {
                sectionModel.isSectionExpand = YES;
            } else {
                sectionModel.isSectionExpand = NO;
            }
            
            [self.tranferSuccessRecordModelArray addObject:sectionModel];
        }
        [self.transferDetailTableView reloadData];
    }
    
    if ([self.transferDetailModel.creditor.status isEqualToString:@"已撤销"]) {//已撤销
        self.statusImgView.hidden = NO;
    }else {
        self.statusImgView.hidden = YES;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.tranferSuccessRecordModelArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return self.tranferSuccessRecordModelArray.count;
    
    MNDInvestmentSectionModel *model = self.tranferSuccessRecordModelArray[section];
    if (model.isSectionExpand) {
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    MNDTransferSuccessRecordModel *model = self.tranferSuccessRecordModelArray[indexPath.row];
    MNDTransferSuccessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDTransferSuccessCell"];
    
    MNDInvestmentSectionModel *model = self.tranferSuccessRecordModelArray[indexPath.section];
    MNDTransferSuccessRecordModel *recordModel = model.transferSuccessModel;
    
    cell.principalLabel.text = [NSString stringWithFormat:@"转让本金: %@", recordModel.principal];
    cell.accruedInterestLabel.text = [NSString stringWithFormat:@"应计利息: %@", recordModel.accrued_interest];
    cell.timeLabel.text = [NSString stringWithFormat:@"转让日期: %@", recordModel.time];
    cell.servefeeLabel.text = [NSString stringWithFormat:@"转让费用: %@", recordModel.servefee];
    cell.discountLabel.text = [NSString stringWithFormat:@"折扣金额: %@", recordModel.discount];
    cell.userName.text = [NSString stringWithFormat:@"转入者: %@", recordModel.user_name];
    
    return cell;
}

-(void)setupUI {

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    MNDTransferHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    
//    MNDTransferSuccessRecordModel *model = self.tranferSuccessRecordModelArray[section];
    if (!headerView) {
        headerView = [[MNDTransferHeaderView alloc] initWithReuseIdentifier:@"header"];
        
    }
    MNDInvestmentSectionModel *sectionModel = self.tranferSuccessRecordModelArray[section];
    headerView.model = sectionModel;
    
    headerView.headerClickBlock = ^(BOOL expand) {
        [self updateTableViewSection:section];
    };
    
    MNDTransferSuccessRecordModel *model = sectionModel.transferSuccessModel;
    NSString *headerTitle = [NSString stringWithFormat:@"%zd-%@", section + 1, model.status];
    headerView.transferStatusLabel.text = headerTitle;
    
    return headerView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 60.0;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    
//    
//    if (self.tranferSuccessRecordModelArray.count == 0) {
//        return 0;
//    }else {
//    return 60;
//    }
//}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    MNDTransferFootView *footView = [[MNDTransferFootView alloc]initWithReuseIdentifier:@"footer"];
//    if (!footView) {
//        footView = [[MNDTransferFootView alloc] initWithReuseIdentifier:@"footer"];
//    }
//    footView.backgroundColor = [UIColor redColor];
//    return footView;
//}
//更新数据
- (void)updateTableViewSection:(NSInteger)section {
    //    [self.tableView beginUpdates];
    [self.transferDetailTableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    //    [self.tableView endUpdates];
}

- (void)cancelTransferAction:(id)sender {
    if (self.transferDetailModel) {
        kdeclare_weakself;
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"您确定要撤销转让该项目吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *comfirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [NetworkProgressHUD showHud];
            //取消转让接口调用
            NSDictionary *params = [MNDSign signedParamWithDict:@{@"creditor_id": weakSelf.creditorId}];
            
            [APIManager sendRequestWithPath:API_TENDER_TRANSFER_CANCEL parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
                if (responseModel.status == ResponseSuccess) {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                } else {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                }
            } onFailure:^(NSError *error) {
                [NetworkProgressHUD showHudNetworkError:error];
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:comfirmAction];
        [alertVC addAction:cancelAction];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }
   
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
